import React from "react";
import { Modal, Form, Input, TreeSelect } from "antd";

import { usePageContext } from "../hooks/useContext";
import { useForm } from "../hooks/useForm";
import { useCreate } from "../hooks/useCreate";
import { useUpdate } from "../hooks/useUpdate";

const FormModal = ({ authorities, form }) => {
  const { handleClose } = useForm();
  const {
    state: {
      modalOpen,
      form: { handleSubmit, isEdit }
    }
  } = usePageContext();
  useCreate({ form });
  useUpdate({ form });

  const { getFieldDecorator } = form;

  return (
    <Modal
      title={isEdit ? "编辑角色" : "新建角色"}
      centered
      visible={modalOpen}
      onOk={handleSubmit}
      onCancel={handleClose}
      okText="确认"
      cancelText="取消"
    >
      <Form layout="vertical">
        <Form.Item label="名称">
          {getFieldDecorator("name", {
            rules: [{ required: true, message: "请输入名称！" }]
          })(
            <Input
              addonBefore="ROLE_"
              placeholder="输入名称..."
              disabled={isEdit}
            />
          )}
        </Form.Item>
        <Form.Item label="描述">
          {getFieldDecorator("description", {
            rules: [{ required: true, message: "请输入描述！" }]
          })(<Input placeholder="输入描述..." />)}
        </Form.Item>
        <Form.Item label="权限">
          {getFieldDecorator("authorityIds", {
            rules: [{ required: true, message: "请至少选择一个权限！" }]
          })(
            <TreeSelect
              treeCheckable={true}
              treeData={authorities}
              placeholder="选择权限..."
              showCheckedStrategy="SHOW_CHILD"
            />
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
};

const WrappedForm = Form.create({ name: "modal" })(FormModal);

export default WrappedForm;
